﻿using Selenium.NET.Service;
using Selenium.NET.Service.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Selenium.NET.WinFormTest
{
    public class CookieHelper
    {
        /// <summary>
        /// Cookies转为字符串
        /// </summary>
        /// <param name="driver">当前浏览器对象</param>
        /// <returns>返回转换后的字符串</returns>
        public static string CookiesToString(Cookies cookies)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cookies.Count; i++)
            {
                //Cookie与Cookie以{;;}隔开，Cookie内的每个内容以{;}隔开
                sb.Append(cookies[i].Name + "{;}");
                sb.Append(cookies[i].Value + "{;}");
                sb.Append(cookies[i].Domain + "{;}");
                sb.Append(cookies[i].Path + "{;}");
                sb.Append(cookies[i].Expiry + "{;;}");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 给浏览器设置Cookies
        /// </summary>
        /// <param name="list">要设置的Cookies集合</param>
        /// <param name="driver">当前浏览器对象</param>
        public static void SetCookies(string allCookies, WebDriver driver)
        {
            var list = Regex.Split(allCookies, "{;;}", RegexOptions.IgnoreCase).ToList();
            foreach (var cookies in list.Where(c => !string.IsNullOrEmpty(c)))
            {
                string[] thisCookie = Regex.Split(cookies, "{;}", RegexOptions.IgnoreCase);
                driver.Manage.AddCookie(thisCookie[0], thisCookie[1], thisCookie[2], thisCookie[3], thisCookie[4]);
            }
        }

    }
}
